<?php

namespace App\Listener;

use App\Utils\LoggerUtil;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Hyperf\Validation\Event\ValidatorFactoryResolved;
use Hyperf\Validation\Validator;

#[Listener]
class ValidatorFactoryResolvedListener implements ListenerInterface
{

    public function listen(): array
    {
        return [
            ValidatorFactoryResolved::class,
        ];
    }

    public function process(object $event): void
    {
        /**  @var ValidatorFactoryInterface $validatorFactory */
        $validatorFactory = $event->validatorFactory;
        // 注册了 phone 验证器
        $validatorFactory->extend('phone_number', function (string $attribute, mixed $value, array $parameters, Validator $validator): bool {
            if (strlen($value) != $parameters[0]) {
                return false;
            }
            $pregResult = preg_match('/^1[3-9]\d{9}$/', $value);
            // false则返回错误信息;true表示验证通过
            return !empty($pregResult);
        });
        // 当创建一个自定义验证规则时，你可能有时候需要为错误信息定义自定义占位符这里扩展了 :phone 占位符
        // $validatorFactory->replacer('phone_number', function (string $message, string $attribute, string $rule, array $parameters): array|string {
        //     return str_replace(':phone_number', $attribute, $message);
        // });
    }
}
